package cn.hfatec.shms.web.yk.ykTj.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.organization.model.Organization;
import cn.hfatec.shms.system.organization.service.OrganizationService;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.web.yk.ykJkgl.model.YkJkglParams;
import cn.hfatec.shms.web.yk.ykTj.model.YkTj;
import cn.hfatec.shms.web.yk.ykTj.model.YkTjParams;
import cn.hfatec.shms.web.yk.ykTj.service.YkTjService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/yk/ykTj")
public class YkTjAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "YkTjService")
    private YkTjService ykTjService;

    //服务层
    @Resource(name = "OrganizationService")
    private OrganizationService organizationService;

    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(YkTjParams ykTjParams, Page page, Model model) {

        Table table = ykTjService.queryYkTjTable(ykTjParams, page);
        YkTj ykTj = ykTjService.hjYkTjTable(ykTjParams);
        model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
        model.addAttribute("AKTypeList", CodeInfoCache.getCodeInfo(CodeType.AK_TYPE));
        model.addAttribute("jkglTypeList", CodeInfoCache.getCodeInfo(CodeType.JKGL_TYPE));
        model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
        model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.TKQD_TYPE));
        model.addAttribute("ynTypeList", CodeInfoCache.getCodeInfo(CodeType.YN_TYPE));
        model.addAttribute("ykTjsTable", table);
        model.addAttribute("ykTjHj", ykTj);
        model.addAttribute("ykTjParams", ykTjParams);
        return "/yk/ykTj/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(YkTjParams ykTjParams, Page page, Model model) {
        try {
            list(ykTjParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykTj/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            YkTj ykTj = new YkTj();
            ykTj.setProductName("体检");
            ykTj.setChannelType("1");
            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("AKTypeList", CodeInfoCache.getCodeInfo(CodeType.AK_TYPE));
            model.addAttribute("jkglTypeList", CodeInfoCache.getCodeInfo(CodeType.JKGL_TYPE));
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.TKQD_TYPE));
            model.addAttribute("ynTypeList", CodeInfoCache.getCodeInfo(CodeType.YN_TYPE));
            model.addAttribute("ykTj", ykTj);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykTj/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            YkTj ykTj = ykTjService.getYkTj(id);
            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("AKTypeList", CodeInfoCache.getCodeInfo(CodeType.AK_TYPE));
            model.addAttribute("jkglTypeList", CodeInfoCache.getCodeInfo(CodeType.JKGL_TYPE));
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.TKQD_TYPE));
            model.addAttribute("ynTypeList", CodeInfoCache.getCodeInfo(CodeType.YN_TYPE));

            model.addAttribute("ykTj", ykTj);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykTj/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteYkTj(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            ykTjService.deleteYkTjBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveYkTj(@Valid YkTj ykTj, BindingResult result, HttpServletRequest request) throws NotAuthException {
        try {
            User user = (User) request.getSession().getAttribute(SysContant.LOGIN_USER_SESSION);
            if (user == null) {
                throw new NotAuthException("用户未授权");
            } else {
                Organization organization = organizationService.getOrganizationByOrgId(user.getOrgId());
                ykTj.setOrgLevelCode(organization.getOrgLevelCode());
            }
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            return ykTjService.saveYkTj(ykTj, user);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据YkTj保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }

    }

    /**
     * 导入潜在客户
     *
     * @param path
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/importTJ")
    @ResponseBody
    public String importCustom(String path, HttpServletRequest request, HttpServletResponse response) {

        try {

            return ykTjService.importCust(path, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据Custom保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
    }

    /**
     * 导入模板下载
     *
     * @param request
     * @param response
     * @param serverFileName
     * @param clientFileName
     * @return
     */
    @RequestMapping("/downloadTemplate")
    @ResponseBody
    public String downloadTemplate(HttpServletRequest request, HttpServletResponse response, String serverFileName, String clientFileName) {
        FileInputStream fileInputStream = null;
        String msg = "";
        try {

            File file = new File(request.getSession().getServletContext().getRealPath("") + File.separator + "WEB-INF" + File.separator + "content" + File.separator + "yk" + File.separator + "ykTj" + File.separator + serverFileName);

            long fileLength = file.length();

            // 设置下载参数
            clientFileName = encodeFilename(request, clientFileName);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName);
            response.addHeader("Content-Length", "" + fileLength);
            response.setContentType("application/octet-stream;charset=UTF-8");
            // response.setContentType("application/x-msdownload");

            fileInputStream = new FileInputStream(file);
            OutputStream out = response.getOutputStream();

            // 读文件
            int iBufferSize = 65000;
            byte[] buffer = new byte[65000];
            long lReadLen = 0;
            while (lReadLen < fileLength) {
                int lRead = fileInputStream.read(buffer, 0, iBufferSize);
                lReadLen += lRead;
                out.write(buffer, 0, lRead);
            }
            out.flush();

        } catch (Exception e) {
            logger.error("下载文件失败!", e);
            msg = "下载文件失败!<a href='#' onclick='javascript:history.go(-1);'>返回</a><br/>";
            msg += e.getMessage();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
            }
        }

        return msg;
    }

    /**
     * 导出excel
     */
    @RequestMapping("/export")
    @ResponseBody
    public String export(YkTjParams ykTjParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            ykTjService.exportExcel(ykTjParams, request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
}
